/**
 * Copyright (c) 2008, Julien PORTALIER
 * http://featherphp.googlecode.com/
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

/*if (!Textarea) { Textarea = {}; }*/

// autoresize of textarea elements
Textarea.Maxlength = new Class(
{
	initialize: function(textarea)
	{
		this.textarea  = $(textarea);
		this.maxlength = this.textarea.getAttribute('maxlength');
		
		this.textarea.addEvent('keypress', this._checkLength.bindWithEvent(this));
		this.textarea.addEvent('keyup',    this._checkPaste.bindWithEvent(this));
	},
	
	_checkLength: function(evt)
	{
		if (this.textarea.value.length >= this.maxlength)
		{
			if (!evt.control && !evt.shift && !evt.meta && !evt.alt)
			{
				switch(evt.key)
				{
					case 'up': case 'down': case 'left': case 'right':
					case 'backspace': case 'delete': case 'esc':
					case 'home': case 'end':
						break;
					default:
						evt.stop();
				}
			}
		}
	},
	
	_checkPaste: function (evt)
	{
		if (this.textarea.value.length >= this.maxlength) {
			this.textarea.value = this.textarea.value.substring(0, this.maxlength);
		}
	}
});

// auto binds textareas
window.addEvent("domready", function()
{
	$$("textarea").each(function(textarea)
	{
		if (textarea.getAttribute('maxlength')) {
			new Textarea.Maxlength(textarea);
		}
	});
});
